﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdate.Utility.Security
{
    using System.Security.Cryptography;

    using AutoUpdate.Utility.Helper;
    public class DES
    {
        /// <summary>
        /// 默认密钥向量
        /// </summary>
        private static readonly byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

        /// <summary>
        /// 3des加密算法
        /// </summary>
        private static byte[] Encrypt(string content, byte[] key, CipherMode mode = CipherMode.CBC)
        {
            if (UIUtils.IsNull(content))
            {
                return null;
            }

            if (key == null || key.Length == 0)
            {
                return null;
            }

            try
            {
                using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
                {
                    des.Key = key;
                    des.Mode = mode;
                    des.IV = iv;

                    var desEncrypt = des.CreateEncryptor();
                    var buffer = AES.ToByte(content);
                    return desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }


        /// <summary>
        /// 3des解密算法
        /// </summary>
        private static byte[] Decrypt(string content, byte[] key, CipherMode mode = CipherMode.CBC)
        {

            if (UIUtils.IsNull(content))
            {
                return null;
            }

            if (key == null || key.Length == 0)
            {
                return null;
            }

            try
            {
                using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
                {
                    des.Key = key;
                    des.Mode = mode;
                    des.IV = iv;
                    des.Padding = PaddingMode.PKCS7;

                    var desDecrypt = des.CreateDecryptor();
                    byte[] buffer = Convert.FromBase64String(content);

                    return desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }


   
    }
}
